import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { resolve } from 'path'
import { visualizer } from 'rollup-plugin-visualizer'
import { VitePWA } from 'vite-plugin-pwa'
// import pxtorem from 'postcss-pxtorem'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    react({
      // 启用React Fast Refresh
      fastRefresh: true,
      // 启用JSX运行时优化
      jsxRuntime: 'automatic',
      // React 19 兼容性配置
      babel: {
        plugins: [
          // 确保与React 19的兼容性
        ],
      },
    }),

    // PWA支持
    VitePWA({
      registerType: 'autoUpdate',
      workbox: {
        globPatterns: ['**/*.{js,css,html,ico,png,svg}'],
        runtimeCaching: [
          {
            urlPattern: /^https:\/\/api\./,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'api-cache',
              expiration: {
                maxEntries: 10,
                maxAgeSeconds: 60 * 60 * 24 * 365, // 1 year
              },
            },
          },
        ],
      },
      includeAssets: ['favicon.ico', 'apple-touch-icon.png', 'masked-icon.svg'],
      manifest: {
        name: 'Health App',
        short_name: 'Health',
        description: 'Health management application',
        theme_color: '#ffffff',
        background_color: '#ffffff',
        display: 'standalone',
        icons: [
          {
            src: 'pwa-192x192.png',
            sizes: '192x192',
            type: 'image/png',
          },
          {
            src: 'pwa-512x512.png',
            sizes: '512x512',
            type: 'image/png',
          },
        ],
      },
    }),

    // 构建分析插件
    process.env.ANALYZE === 'true' && visualizer({
      filename: 'dist/stats.html',
      open: true,
      gzipSize: true,
      brotliSize: true,
    }),
  ].filter(Boolean),

  // 路径别名配置
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
      '@components': resolve(__dirname, 'src/compontent'),
      '@pages': resolve(__dirname, 'src/pages'),
      '@utils': resolve(__dirname, 'src/utils'),
      '@api': resolve(__dirname, 'src/api'),
      '@store': resolve(__dirname, 'src/store'),
      '@types': resolve(__dirname, 'src/types'),
    },
  },

  // 构建优化配置
  build: {
    // 启用压缩
    minify: 'terser',
    terserOptions: {
      compress: {
        // 移除console.log
        drop_console: true,
        // 移除debugger
        drop_debugger: true,
        // 移除未使用的代码
        pure_funcs: ['console.log', 'console.info'],
      },
    },

    // 代码分割配置
    rollupOptions: {
      output: {
        // 手动分包
        manualChunks: {
          // React相关库
          'react-vendor': ['react', 'react-dom', 'react-router-dom'],
          // Redux相关库
          'redux-vendor': ['@reduxjs/toolkit', 'react-redux', 'redux', 'redux-persist'],
          // UI库
          'ui-vendor': ['antd', 'antd-mobile', '@ant-design/icons'],
          // 工具库
          'utils-vendor': ['axios', 'js-md5', 'jsencrypt'],
          // 其他第三方库
          'vendor': ['openai', 'amfe-flexible'],
        },
        // 资源文件命名
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/js/[name]-[hash].js',
        assetFileNames: (assetInfo) => {
          const info = assetInfo.name.split('.')
          const ext = info[info.length - 1]
          if (/\.(png|jpe?g|gif|svg|webp|ico)$/i.test(assetInfo.name)) {
            return `assets/images/[name]-[hash].${ext}`
          }
          if (/\.(css)$/i.test(assetInfo.name)) {
            return `assets/css/[name]-[hash].${ext}`
          }
          return `assets/[name]-[hash].${ext}`
        },
      },
    },

    // 设置chunk大小警告限制
    chunkSizeWarningLimit: 1000,

    // 启用CSS代码分割
    cssCodeSplit: true,

    // 启用source map（生产环境可关闭）
    sourcemap: false,

    // 启用gzip压缩
    reportCompressedSize: true,
  },

  // CSS配置
  css: {
    // 启用CSS模块化
    modules: {
      localsConvention: 'camelCase',
    },
    // PostCSS配置
    postcss: {
      plugins: [
        // pxtorem({
        //   rootValue: 47.5,
        //   propList: ['*'],
        // }),
      ],
    },
  },

  // 开发服务器配置
  server: {
    // 启用HMR
    hmr: true,

    // 端口配置
    port: 3000,
    host: true,

    // 代理配置
    proxy: {
      '/api': {
        target: 'http://10.59.9.18',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
      '/kimi-api': {
        target: 'https://api.moonshot.cn',
        changeOrigin: true,
        secure: true,
        rewrite: (path) => path.replace(/^\/kimi-api/, '/v1'),
        configure: (proxy, _options) => {
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log('代理请求:', req.method, req.url);
            console.log('目标URL:', proxyReq.path);
          });
          proxy.on('proxyRes', (proxyRes, req, res) => {
            console.log('代理响应:', proxyRes.statusCode, req.url);
            // 添加CORS头
            res.setHeader('Access-Control-Allow-Origin', '*');
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
            res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
          });
          proxy.on('error', (err, req, res) => {
            console.error('代理错误:', err);
          });
        },
      },
    },
  },

  // 依赖预构建优化
  optimizeDeps: {
    // 预构建依赖
    include: [
      'react',
      'react-dom',
      'react-router-dom',
      '@reduxjs/toolkit',
      'react-redux',
      'antd',
      'antd-mobile',
      'axios',
    ],
    // 排除不需要预构建的依赖
    exclude: ['@ant-design/icons'],
  },

  // 环境变量配置
  define: {
    // 定义全局常量
    __DEV__: JSON.stringify(process.env.NODE_ENV === 'development'),
  },
})
